/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ru.dusty.fs.mkdir;

import java.io.FileNotFoundException;
import java.io.IOException;
import ru.dusty.fs.filesystem.data.BlocksMap;
import ru.dusty.fs.filesystem.exceptions.FileAlreadyExistsException;
import ru.dusty.fs.filesystem.utils.Utils;

/**
 *
 * @author vadim
 */
public class MkdirFs {
    
    private static final String NAME = "mkdir";
    
    private BlocksMap map;
    
    public int mkdir(String[] args) {
        if (args.length < 2) {
            System.out.println(NAME + ": missing operand after \"" + NAME + "\"");
            System.out.println(NAME + ": use \"" + NAME + " root path...\"");
            return 1;
        }
        
        String root = args[0];
        
        try {
            if (!Utils.isFsFormatted(root)) {
                System.out.println(NAME + ": File system error.");
                System.out.println(NAME + ": Use the command \"format root\"");
                return 5;
            }
            
            map = new BlocksMap(root, Utils.getBlocksCount(root));
            map.initMap();
            for (int i = 1; i < args.length; i++) {
                Utils.createDir(root, map, Utils.parsePath(args[i]));
                System.out.println(NAME + ": directory " + args[i] + " has been successfully created.");
            }
        } catch (FileAlreadyExistsException ex) {
            System.out.println(NAME + ": Unable to create the specified directory.");
            System.out.println(NAME + ": " + ex.getFile() + ": such file already existed.");
            return 7;
        } catch (FileNotFoundException ex) {
            System.out.println(NAME + ": Could not find the file block.");
            System.out.println(NAME + ": " + ex.getMessage());
            return 2;
        } catch (OutOfMemoryError ex) {
            System.out.println(NAME + ": Memory error.");
            System.out.println(NAME + ": " + ex.getMessage());
            return 8;
        } catch (IOException ex) {
            System.out.println(NAME + ": Error occurred while reading the file block.");
            System.out.println(NAME + ": " + ex.getMessage());
            return 3;
        }
        
        return 0;
    }
    
}
